<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<view style="background-color: #fff;">
			<u-form class="form bg-white" :model="model" ref="uForm" label-position="left" style="padding: 0 36rpx;">
				<u-form-item label="公司:" prop="companyCode" label-width="180" required
					:label-style="{'font-weight':'bold'}">
					<js-select v-model="model.companyCode" :showFilter="false" :items="companySelectList"
						placeholder="请选择" :tree="true" :label-value="model['company.companyName']"
						@label-input="model['company.companyName'] = $event"
						@confirm="selectcompanyConfirm"></js-select>
				</u-form-item>

				<u-form-item label="仓库:" prop="whcode" label-width="180" :label-style="{ 'font-weight': 'bold' }" required>
					<js-select v-model="model.whcode" :showFilter="false" :items="basWarehouseSelectList" placeholder="请选择" :tree="true"
						:label-value="model['whname']" @label-input="model['whname'] = $event" @confirm="selectConfirm"></js-select>
				</u-form-item>

				<view class="form-row">
					<view class="form-row-content">
						<u-form-item label="商品:" prop="invName" label-width="150" :label-style="{ 'font-weight': 'bold' }" required>
							<u-search search-icon='' v-model="model.invName" placeholder="请扫描" :disabled="true" clearabled :show-action="false" bgColor="#fff"></u-search>
							<u-icon @click="xzsp" name="search" size="70"></u-icon>
						</u-form-item>
					</view>
				</view>

				<u-form-item label="形象刊:" prop="freeVO" label-width="180">
					<u-input v-model="model.freeVO.cfree1" type="text" placeholder="请输入" clearable />
				</u-form-item>

				<view class="form-row">
					<view class="form-row-content">
						<u-form-item label="当前货位:" prop="posName" label-width="180" :label-style="{ 'font-weight': 'bold' }" required>
							<u-search search-icon='' v-model="model.beforePosName" placeholder="请扫描" :disabled="true" clearabled :show-action="false" bgColor="#fff"></u-search>
							<div class="quantity-display">{{ model.beforePosIqty }}</div>
							<u-icon @click="xzhw" name="search" size="70"></u-icon>
						</u-form-item>
					</view>
				</view>

				<view class="form-row">
					<view class="form-row-content">
						<u-form-item label="目标货位:" prop="newPosName" label-width="180" :label-style="{ 'font-weight': 'bold' }" required>
							<u-search search-icon='' v-model="model.afterPosName" placeholder="请扫描" :disabled="true" clearabled :show-action="false" bgColor="#fff"></u-search>
							<div class="quantity-display">{{ model.afterPosIqty }}</div>
							<u-icon @click="xzhw('tz')" name="search" size="70"></u-icon>
						</u-form-item>
					</view>
				</view>

				<u-form-item label="转移数量:" prop="iqty" label-width="180" :label-style="{ 'font-weight': 'bold','color':'red' }" required>
					<u-input v-model="model.iqty" type="number" placeholder="请输入" @input="replaceInput" clearable />
				</u-form-item>
			</u-form>
		</view>
		<!-- 悬浮按钮区域 -->
		<view class="floating-buttons">
			<movable-area class="movable-area">
				<movable-view class="movable-view" :x="x" :y="y2" direction="all">
					<u-button size="mini" @click="getPosValue(1)" type="info" class="float-btn">当前货位</u-button>
				</movable-view>
			</movable-area>
			<movable-area class="movable-area">
				<movable-view class="movable-view" :x="x" :y="y1" direction="all">
					<u-button size="mini" @click="getPosValue(2)" type="info" class="float-btn">目标货位</u-button>
				</movable-view>
			</movable-area>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x1" :y="y" direction="all">
					<u-button size="mini" @click="xcl" type="success" class="float-btn">存量</u-button>
				</movable-view>
			</movable-area>
			<movable-area class="movable-area">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button v-if="!isSubmitting" size="mini" @click="submit" type="primary" class="float-btn-primary">确定</u-button>
					<u-button v-else size="mini" type="info" class="float-btn-primary" :disabled="true">提交中...</u-button>
				</movable-view>
			</movable-area>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				posValue: 1,
				companySelectList: [],
				stockListHeight: 0,
				barCode: "",
				model: {
					parent: {},
					freeVO: {}
				},
				// 悬浮按钮坐标
				x: 650,
				y: 650,
				x1: 0,
				y1: 465,
				y2: 390,
				basWarehouseSelectList: [],
				isSubmitting: false, // 防止重复提交标志
			};
		},
		onLoad() {
			this.model.companyCode = this.vuex_company.companyCode || '';
			this.getBasWarehouseTreeData();

			// 监听商品选择事件
			uni.$on('xzsp', (e) => {
				this.model.invCode = e.invCode;
				this.model.invName = e.invName;
				this.model.viewCode = e.viewCode;
				// 把货位信息置空
				this.selectConfirm();
				this.$forceUpdate();
			});

			// 监听货位选择事件
			uni.$on('hwObjs', async (e) => {
				try {
					// 检查事件数据是否有效
					if (!e || !e[0] || !e[0]['id']) {
						console.error('hwObjs event data is invalid:', e);
						return;
					}
					console.log('hwObjs',e)
					const iqty = await this.getPosIqty(e[0]['name']);

					if (e[0]['type'] == 'tz') {
						this.model = {
							...this.model,
							afterPos: e[0]['id'],
							afterPosName: e[0]['name'],
							afterPosIqty: iqty,
						};
					} else {
						this.model = {
							...this.model,
							beforePos: e[0]['id'],
							beforePosName: e[0]['name'],
							beforePosIqty: iqty,
						};
					}
					this.$forceUpdate();
				} catch (error) {
					console.error('Error in hwObjs event handler:', error);
				}
			});

			// 获取屏幕高度
			const _self = this;
			uni.getSystemInfo({
				success: (e) => {
					_self.stockListHeight = e.windowHeight - uni.upx2px(160);
				},
				fail: () => {}
			});
		},
		watch: {},
		onShow() {
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			
			
			this.$u.api.ktnw.companyTreeData().then(res => {
				this.companySelectList = res;
			});
		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onReady() {},
		computed: {
			...mapState(['vuex_basWare'])
		},
		methods: {
			async getPosIqty(posName) {
				// 改为posName
				console.log(this.model,'this.model')
				try {
					const res = await this.$u.api.ktnw.findActual({
						'companyCode': this.model?.companyCode || '',
						'invName': this.model?.invName || '',
						'viewCode': this.model?.viewCode || '',
						'cwhname': this.model?.whname || '',
						'cfree1': this.model?.freeVO?.cfree1 || '',
						'posName': posName,
					});

					// 检查返回数据是否存在
					if (res && res.list && res.list.length > 0 && res.list[0]) {


						return parseInt(res.list[0]['iqty'] || 0);
					}
					return 0; // 如果没有数据，返回默认值

				} catch (error) {
					console.error('Error fetching position quantity:', error);
					return 0; // 在出错时返回默认值
				}
			},
			getPosValue(type){
				this.posValue = type
			},
			selectcompanyConfirm() {
				this.model.invCode = ''
				this.model.invName = ''
				this.model.viewCode = ''
				this.$forceUpdate()
			},
			xcl(){
				if(!this.model.invName){
					this.$u.toast('请先选择商品！');
					return ;
				}
				
				// let whname = this.model.whname || ''
				// uni.navigateTo({
				// 	url: "/pagesData/data/stockListData?whname=" + whname + '&invName='+ this.model.invName + '&invCode='+ this.model.invCode,
				// });
				let cwhname = this.model.whname || ''
				let beforePos = this.model.beforePosName || ''
				console.log('beforePos',this.model)
				uni.navigateTo({
					url: "/pagesData/data/posListData?posName=" + beforePos + '&cwhname='+ cwhname +'&invName='+ this.model.invName + '&invCode='+ this.model.viewCode,
				});
			},
			xzhw(type){
				if(!this.model.whcode){
					this.$u.toast('请先选择仓库！');
					return ;
				}
				// if(type == 'tz' && !this.model.posName && !this.model.invName){
				// 	this.$u.toast('请选择调整前货位和商品！');
				// 	return ;
				// }
				if(type){
					uni.navigateTo({
						url: "/pages/ktnw/qtsj/hwXz?whcode=" + this.model.whcode + '&type='+ type,
					});
				}else{
					uni.navigateTo({
						url: "/pages/ktnw/qtsj/hwXz?whcode=" + this.model.whcode,
					});
				}
				
			},
			xzsp(){
				if (!this.model.companyCode) {
					this.$u.toast('请先选择公司！');
				}else{
					uni.navigateTo({
						url: "/pages/ktnw/qtsj/xzspList?companyCode=" + this.model.companyCode,
					});
				}
			},
			getBasWarehouseTreeData(){
				this.$u.api.ktnw.basWarehouseTreeData({
					isLoadUser: true,
					userIdPrefix: '' 
				}).then(res => {
					this.basWarehouseSelectList = res
				})
			},
			replaceInput(e) {
				console.log(e);
				var that = this
				e = e.match(/^\d*(\.?\d{0,2})/g)[0]
				this.$nextTick(() => {
					that.model.iqty = e
				})
			
			},
			/** 发生声音*/
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			selectConfirm() {
				// 清空货位信息
				this.model.beforePos = '';
				this.model.beforePosName = '';
				this.model.afterPos = '';
				this.model.afterPosName = '';
				this.model.beforePosIqty = '';
				this.model.afterPosIqty = '';
			},
			invCode(bar, companyCode) {
				let InventoryPrefix = this.vuex_config.InventoryPrefix;
				if (bar.indexOf(InventoryPrefix) != -1) {
					return bar
				} else {
					let code = `inv_${companyCode}_${bar}`
					return code
				}
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code
				
				//判断条形码长度是否大于3
				if(barcode.length > 3){
					//去除换行符
					let newString = barcode.replace('\n;', '');
					
					this.barCode = newString;
					this.confirm()
					//将换行符分割成数组
					// const allItems = newString.split('\n');
					// 	//遍历数组，将每一项添加到arr中
					// 	for(let i = 0;i<allItems.length;i++){
					// 		this.arr.push({
					// 			"content":allItems[i],
					// 			"remarks":this.remarks
					// 		})
					// 	}
				}
			},
			confirm() {
				const _that = this;
				const PositionPrefix = _that.vuex_config.PositionPrefix;
				const InvBarType = _that.vuex_config.InvBarType;
				const PosBarType = _that.vuex_config.PosBarType;
				const bar = encodeURIComponent(this.barCode);

				if (bar.indexOf(PositionPrefix) != -1) {
					if(this.posValue == 1){
						this.$u.api.ktnw.getBarInfo({
							barCode: bar,
							barType: PosBarType,
							whCode:this.model.whcode || '',
						}).then(async (res) => {
							if(res.result == 'true'){
								if(res.data?.basPos?.treeLeaf == '0') {
									this.$forceUpdate()
									_that.sendMp3('sb');
									let message = '请扫描末级货位'
									_that.$refs.jsError.showError("", message, "error");
									return;
								}
								_that.sendMp3('cg');
								this.model.whcode = res.data.basWare.cwhcode
								this.model.beforePos = res.data.basPos.posCode
								this.model.beforePosName = res.data.basPos.posName
								try {
									const iqty = await this.getPosIqty(res.data.basPos.posName);
									this.model.beforePosIqty = iqty;
								} catch (error) {
									console.error('Error getting position quantity:', error);
									this.model.beforePosIqty = 0;
								}
								this.$forceUpdate()
							}else{
								// _that.model.beforePosName = ''
								this.$forceUpdate()
								_that.sendMp3('sb');
								let message = res.message
								_that.$refs.jsError.showError("", message, "error");
							}
							
						})
					}else{
						this.$forceUpdate()
						this.$u.api.ktnw.getBarInfo({
							barCode: bar,
							barType: PosBarType,
							whCode:this.model.whcode || ''
						}).then(async (res) => {
							if(res.result == 'true'){
								if(res.data?.basPos?.treeLeaf == '0') {
									this.$forceUpdate()
									_that.sendMp3('sb');
									let message = '请扫描末级货位'
									_that.$refs.jsError.showError("", message, "error");
									return;
								}
								_that.sendMp3('cg');
								this.model.whcode = res.data.basWare.cwhcode
								this.model.afterPos = res.data.basPos.posCode
								this.model.afterPosName = res.data.basPos.posName
								try {
									const iqty = await this.getPosIqty(res.data.basPos.posName);
									this.model.afterPosIqty = iqty;
								} catch (error) {
									console.error('Error getting position quantity:', error);
									this.model.afterPosIqty = 0;
								}
								this.$forceUpdate()
								
							}else{
								// _that.model.beforePosName = ''
								this.$forceUpdate()
								_that.sendMp3('sb');
								let message = res.message
								_that.$refs.jsError.showError("", message, "error");
							}
						})
					}
					
					
				}else{
					if (!this.model.companyCode) {
						setTimeout(()=>{
							_that.model.invName = ''
							_that.$forceUpdate()
						},500)
						_that.sendMp3('sb');
						_that.$refs.jsError.showError("", "请先选择公司", "error");
						return;
					}
					let barCode = this.invCode(bar, this.model.companyCode)
					this.$u.api.ktnw.getBarInfo({
						barCode: barCode,
						barType: InvBarType,
						companyCode: this.model.companyCode
					}).then((res) => {
						if(res.result == 'true'){
							_that.sendMp3('cg');
							if(this.model.invCode != res.data.basInv.invCode){
								this.selectConfirm()
							}

							this.model.invCode = res.data.basInv?res.data.basInv.invCode:''
							this.model.invName = res.data.basInv?res.data.basInv.invName:''
							this.model.viewCode = res.data.basInv?res.data.basInv.viewCode:''
							// this.model.companyCode = res.data.basInv.companyCode
							// this.model.company = res.data.basInv.company
							this.$forceUpdate()
						}else{
							// _that.model.invName = ''
							this.$forceUpdate()
							_that.sendMp3('sb');
							let message = res.message
							_that.$refs.jsError.showError("", message, "error");
						}
						
					})
				}
			},



			async submit() {
				// 防止重复提交
				if (this.isSubmitting) {
					return;
				}

				if (!this.model.invCode) {
					this.$refs.jsError.showError("", "请先扫描商品", "error");
					return;
				}


				if (!this.model.beforePosName) {
					this.$refs.jsError.showError("", "请先扫描当前货位", "error");
					return;
				}

				if (!this.model.afterPosName) {
					this.$refs.jsError.showError("", "请先扫描目标货位", "error");
					return;
				}

				if (this.model.beforePos == this.model.afterPos) {
					this.$refs.jsError.showError("", "【当前货位】和【目标货位】不能相同", "error");
					return;
				}

				if (!this.model.iqty) {
					this.$refs.jsError.showError("", "请输入转移数量", "error");
					return;
				}

				if (this.model.iqty <= 0) {
					// this.$u.toast('入库数量不能小于等于零！');
					this.$refs.jsError.showError("", "转移数量不能小于等于零", "error");
					return;
				}

				// 设置提交状态为true，防止重复提交并隐藏按钮
				this.isSubmitting = true;

				let data = {
					parent:{
						whcode:this.model.whcode
					},
					freeVO:{
						cfree1:this.model.freeVO.cfree1
					},
					companyCode: this.model.companyCode,
					invCode: this.model.invCode,
					invName: this.model.invName,
					beforePos: this.model.beforePos,
					afterPos: this.model.afterPos,
					iqty: this.model.iqty,
				};

				try {
					const res = await this.$u.api.ktnw.posJustSave(data);

					if (res.result == "true") {
						this.$u.toast(res.message);
						// this.model = {
						// 	parent:{},
						// 	freeVO:{}
						// }
						setTimeout(() => {
							this.model.beforePosName = ''
							this.model.freeVO = {}
							this.model.afterPosName = ''
							this.model.invName = ''
							this.model.invCode = ''
							this.model.viewCode = ''
							// this.model.whcode = ''
							this.model.beforePos = ''
							this.model.afterPos = ''
							this.model.afterPosIqty = ''
							this.model.beforePosIqty = ''
							this.model.iqty = ''
							// 成功后重置提交状态，允许下次提交
							this.isSubmitting = false;
						}, 100);
						// this.sendMp3('sjcg');
						// this.handleFocus()
					} else {
						this.$refs.jsError.showError("", res.message, "error");
						// 失败时重置提交状态，允许重新提交
						this.isSubmitting = false;
					}
				} catch (error) {
					console.error('提交失败:', error);
					this.$refs.jsError.showError("", "提交失败，请重试", "error");
					// 异常时重置提交状态，允许重新提交
					this.isSubmitting = false;
				}
			},
		},
	};
</script>
<style lang="scss">
	$btn_width: 96rpx;
	$btn_height: 96rpx;

	.form-row {
		display: flex;
		justify-content: space-between;

		.form-row-content {
			flex: 1;
		}
	}

	.quantity-display {
		padding: 0 20rpx;
		color: #81b337;
		background: rgba(129, 179, 55, 0.1);
		border-radius: 8rpx;
		font-size: 24rpx;
		margin-right: 20rpx;
	}

	.floating-buttons {
		.movable-area, .movable-area1 {
			height: 97vh;
			width: 650rpx;
			position: fixed;
			top: -20rpx;
			pointer-events: none;

			.movable-view {
				width: $btn_width;
				height: $btn_height;
				pointer-events: auto;
			}
		}

		.movable-area {
			z-index: 999;
			right: $btn_width;
		}

		.movable-area1 {
			z-index: 888;
			left: 20rpx;
		}
	}

	.float-btn {
		width: 90px !important;
		height: 70px !important;
		color: #fff !important;
		font-size: 18px !important;
	}

	.float-btn-primary {
		@extend .float-btn;
		font-size: 20px !important;
	}
</style>